package db

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"log"
	"os"
	"poem-server/comm/global"
	"poem-server/initialize/config"
)

func ElasticInit() {
	// elasticsearch 配置
	var (
		url     = config.Config.Elastic.Url
		sniff   = config.Config.Elastic.Sniff
		health  = config.Config.Elastic.HealthCheckInterval
		errlog  = config.Config.Elastic.ErrLog
		infolog = config.Config.Elastic.InfoLog
	)

	var err error
	global.App.Elastic, err = elastic.NewClient(
		// 设置Elastic服务地址
		elastic.SetURL(url),
		// 是否转换请求地址，默认为true,当等于true时 请求http://ip:port/_nodes/http，将其返回的url作为请求路径
		elastic.SetSniff(sniff),
		// 心跳检查,间隔时间
		elastic.SetHealthcheckInterval(health),
		// 设置错误日志
		elastic.SetErrorLog(log.New(os.Stderr, errlog, log.LstdFlags)),
		// 设置info日志
		elastic.SetInfoLog(log.New(os.Stdout, infolog, log.LstdFlags)),
	)
	if err != nil {
		log.Panic("elasticsearch 连接出现错误~~~", err)
	}
	log.Println("===========>elastic引擎init~", global.App.Elastic)
}

// 测试连接
func TestConnectES() {
	// 健康检查
	do, _ := global.App.Elastic.ClusterHealth().Index().Do(context.TODO())
	fmt.Println("健康检查:", do)
}
